package com.nidu.demo.log.model;

import com.alibaba.cola.exception.BizException;
import com.nidu.demo.base.BaseDeletableEntity;
import com.nidu.demo.base.BaseTenantEntity;
import com.nidu.demo.common.enums.BooleanEnum;
import com.nidu.demo.common.exception.ErrorCodeConstants;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

/**
 * 登录日志领域实体
 *
 * @author auto
 */
@Data
@Accessors(chain = true)
@EqualsAndHashCode(callSuper = true)
public class LoginLog extends BaseTenantEntity implements BaseDeletableEntity {

    private Long id;

    /**
     * 登录类型
     */
    private Integer loginType;

    /**
     * 链路追踪编号
     */
    private String traceId;

    /**
     * 用户编号
     */
    private Long userId;

    /**
     * 用户类型
     */
    private Integer userType;

    /**
     * 用户账号
     */
    private String username;

    /**
     * 登陆结果
     */
    private Boolean result;

    /**
     * 用户 IP
     */
    private String userIp;

    /**
     * 浏览器 UA
     */
    private String userAgent;

    /**
     * 是否删除
     */
    private Boolean deleted;

    @Override
    public void isDeleted() {
        if (BooleanEnum.TRUE.getValue().equals(this.getDeleted())) {
            throw new BizException(ErrorCodeConstants.LOGIN_LOG_NOT_FOUND.getCode(), ErrorCodeConstants.LOGIN_LOG_NOT_FOUND.getMessage());
        }
    }

    /**
     * 创建登录日志
     */
    public static LoginLog create(Integer loginType, String traceId, Long userId, Integer userType,
                                 String username, Boolean result, String userIp, String userAgent) {
        LoginLog loginLog = new LoginLog();
        loginLog.setLoginType(loginType)
                .setTraceId(traceId)
                .setUserId(userId)
                .setUserType(userType)
                .setUsername(username)
                .setResult(result)
                .setUserIp(userIp)
                .setUserAgent(userAgent)
                .setDeleted(BooleanEnum.FALSE.getValue());
        return loginLog;
    }

}
